import { IconButton } from "./button";
import { ErrorBoundary } from "./error";

import styles from "./mask.module.scss";

import DownloadIcon from "../icons/download.svg";
import UploadIcon from "../icons/upload.svg";
import EditIcon from "../icons/edit.svg";
import AddIcon from "../icons/add.svg";
import CloseIcon from "../icons/close.svg";
import DeleteIcon from "../icons/delete.svg";
import DragIcon from "../icons/drag.svg";

import { DEFAULT_MASK_AVATAR } from "../store/mask";
import { ChatMessage, createMessage, ModelType } from "../store";
import { ROLES } from "../client/api";
import { Input, List, ListItem, Modal, Select, showConfirm } from "./ui-lib";
import { Avatar } from "./emoji";
import Locale, { Lang } from "../locales";
import { useNavigate } from "react-router-dom";

import chatStyle from "./chat.module.scss";
import { Dispatch, SetStateAction, useState } from "react";
import { downloadAs, readFromFile } from "../utils";
import { Updater } from "../typing";
import { FileName, Path } from "../constant";
import {
  DragDropContext,
  Droppable,
  Draggable,
  OnDragEndResponder,
} from "@hello-pangea/dnd";
import { MaskTemplate, useMaskTemplateStore } from "../store/maskTemplate";
import { nanoid } from "nanoid";

// drag and drop helper function
function reorder<T>(list: T[], startIndex: number, endIndex: number): T[] {
  const result = [...list];
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
}

export function MaskAvatar(props: { avatar: string; model?: ModelType }) {
  return props.avatar !== DEFAULT_MASK_AVATAR ? (
    <Avatar avatar={props.avatar} />
  ) : (
    <Avatar model={props.model} />
  );
}

export function MaskConfig(props: {
  mask: MaskTemplate;
  updateMask: Updater<MaskTemplate>;
  extraListItems?: JSX.Element;
  readonly?: boolean;
  shouldSyncFromGlobal?: boolean;
}) {
  const updateVariable = () => {
    let result: string[] = [];
    props.mask.context.forEach((e) => {
      const match = matchVariable(e.content);
      if (match && match.length > 0) {
        result = [...result, ...match];
      }
    });
    if (result.length > 0) {
      props.updateMask(
        (mask) =>
          (mask.variables = result!.map((e) => {
            return {
              id: nanoid(),
              var: e,
            };
          })),
      );
    } else {
      props.updateMask((mask) => (mask.variables = []));
    }
  };
  return (
    <>
      <ContextPrompts
        updateVariable={updateVariable}
        context={props.mask.context}
        updateContext={(updater) => {
          const context = props.mask.context.slice();
          updater(context);
          props.updateMask((mask) => (mask.context = context as []));
        }}
      />

      <List>
        <ListItem title={"变量列表"}>
          <div style={{ display: "flex" }}>
            <Select className={chatStyle["context-role"]}>
              {props.mask.variables?.map((e) => {
                return (
                  <option key={e.id} value={e.var}>
                    {e.var}
                  </option>
                );
              })}
            </Select>
          </div>
        </ListItem>
        <ListItem title={"面具模板名称"}>
          <input
            type="text"
            value={props.mask.name}
            onInput={(e) =>
              props.updateMask((mask) => {
                mask.name = e.currentTarget.value;
              })
            }
          ></input>
        </ListItem>
      </List>
    </>
  );
}

function ContextPromptItem(props: {
  index: number;
  prompt: ChatMessage;
  update: (prompt: ChatMessage) => void;
  remove: () => void;
  updateVariable: () => void;
}) {
  const [focusingInput, setFocusingInput] = useState(false);

  return (
    <div className={chatStyle["context-prompt-row"]}>
      {!focusingInput && (
        <>
          <div className={chatStyle["context-drag"]}>
            <DragIcon />
          </div>
          <Select
            value={props.prompt.role}
            className={chatStyle["context-role"]}
            onChange={(e) =>
              props.update({
                ...props.prompt,
                role: e.target.value as any,
              })
            }
          >
            {ROLES.map((r) => (
              <option key={r} value={r}>
                {r}
              </option>
            ))}
          </Select>
        </>
      )}
      <Input
        value={props.prompt.content}
        type="text"
        className={chatStyle["context-content"]}
        rows={focusingInput ? 50 : 1}
        onFocus={() => setFocusingInput(true)}
        onBlur={() => {
          setFocusingInput(false);
          // If the selection is not removed when the user loses focus, some
          // extensions like "Translate" will always display a floating bar
          window?.getSelection()?.removeAllRanges();
          props.updateVariable();
        }}
        onInput={(e) =>
          props.update({
            ...props.prompt,
            content: e.currentTarget.value as any,
          })
        }
      />
      {!focusingInput && (
        <IconButton
          icon={<DeleteIcon />}
          className={chatStyle["context-delete-button"]}
          onClick={() => props.remove()}
          bordered
        />
      )}
    </div>
  );
}

const matchVariable = (str: string) => {
  let pattern = /{{(.*?)}}/g;
  let matches = str.match(pattern);
  if (matches) {
    return matches.map((match) => match.replace(/{{|}}/g, ""));
  }
};
export function ContextPrompts(props: {
  context: ChatMessage[];
  updateContext: (updater: (context: ChatMessage[]) => void) => void;
  updateVariable: () => void;
}) {
  const maskTemplateStore = useMaskTemplateStore();
  const context = props.context;
  const addContextPrompt = (prompt: ChatMessage, i: number) => {
    props.updateContext((context) => context.splice(i, 0, prompt));
  };

  const removeContextPrompt = (i: number) => {
    props.updateContext((context) => context.splice(i, 1));
    props.updateVariable();
  };

  const updateContextPrompt = (i: number, prompt: ChatMessage) => {
    props.updateContext((context) => (context[i] = prompt));
  };

  const onDragEnd: OnDragEndResponder = (result) => {
    if (!result.destination) {
      return;
    }
    const newContext = reorder(
      context,
      result.source.index,
      result.destination.index,
    );
    props.updateContext((context) => {
      context.splice(0, context.length, ...newContext);
    });
  };

  return (
    <>
      <div className={chatStyle["context-prompt"]} style={{ marginBottom: 20 }}>
        <DragDropContext onDragEnd={onDragEnd}>
          <Droppable droppableId="context-prompt-list">
            {(provided) => (
              <div ref={provided.innerRef} {...provided.droppableProps}>
                {context.map((c, i) => (
                  <Draggable
                    draggableId={c.id || i.toString()}
                    index={i}
                    key={c.id}
                  >
                    {(provided) => (
                      <div
                        ref={provided.innerRef}
                        {...provided.draggableProps}
                        {...provided.dragHandleProps}
                      >
                        <ContextPromptItem
                          index={i}
                          prompt={c}
                          update={(prompt) => {
                            updateContextPrompt(i, prompt);
                          }}
                          remove={() => removeContextPrompt(i)}
                          updateVariable={props.updateVariable}
                        />
                        <div
                          className={chatStyle["context-prompt-insert"]}
                          onClick={() => {
                            addContextPrompt(
                              createMessage({
                                role: "user",
                                content: "",
                                date: new Date().toLocaleString(),
                              }),
                              i + 1,
                            );
                          }}
                        >
                          <AddIcon />
                        </div>
                      </div>
                    )}
                  </Draggable>
                ))}
                {provided.placeholder}
              </div>
            )}
          </Droppable>
        </DragDropContext>

        {props.context.length === 0 && (
          <div className={chatStyle["context-prompt-row"]}>
            <IconButton
              icon={<AddIcon />}
              text={Locale.Context.Add}
              bordered
              className={chatStyle["context-prompt-button"]}
              onClick={() =>
                addContextPrompt(
                  createMessage({
                    role: "user",
                    content: "",
                    date: "",
                  }),
                  props.context.length,
                )
              }
            />
          </div>
        )}
      </div>
    </>
  );
}

export function MaskTemplate() {
  const navigate = useNavigate();

  const maskStore = useMaskTemplateStore();
  const maskTemplateStore = useMaskTemplateStore();

  const [filterLang] = useState<Lang>();

  const allMasksTemplate = maskTemplateStore
    .getAll()
    .filter((m) => !filterLang);

  const [editingMaskTemplateId, setEditingMaskTemplateId] = useState<
    string | undefined
  >();
  const editingMask = maskStore.get(editingMaskTemplateId!);
  const closeMaskModal = () => setEditingMaskTemplateId(undefined);

  const downloadAll = () => {
    downloadAs(JSON.stringify(allMasksTemplate), FileName.Masks);
  };

  const importFromFile = () => {
    readFromFile().then((content) => {
      try {
        const importMasks = JSON.parse(content);
        if (Array.isArray(importMasks)) {
          for (const mask of importMasks) {
            if (mask.name) {
              maskStore.create(mask);
            }
          }
          return;
        }
        if (importMasks.name) {
          maskStore.create(importMasks);
        }
      } catch {}
    });
  };

  return (
    <ErrorBoundary>
      <div className={styles["mask-page"]}>
        <div className="window-header">
          <div className="window-header-title">
            <div className="window-header-main-title">{"预设面具模板"}</div>
            <div className="window-header-submai-title">
              {`${allMasksTemplate.length} 个预设面具模板定义`}
            </div>
          </div>

          <div className="window-actions">
            <div className="window-action-button">
              <IconButton
                icon={<DownloadIcon />}
                bordered
                onClick={downloadAll}
                text={Locale.UI.Export}
              />
            </div>
            <div className="window-action-button">
              <IconButton
                icon={<UploadIcon />}
                text={Locale.UI.Import}
                bordered
                onClick={() => importFromFile()}
              />
            </div>
            <div className="window-action-button">
              <IconButton
                icon={<CloseIcon />}
                bordered
                onClick={() => navigate(-1)}
              />
            </div>
          </div>
        </div>

        <div className={styles["mask-page-body"]}>
          <div className={styles["mask-filter"]}>
            <IconButton
              className={styles["mask-create"]}
              icon={<AddIcon />}
              text={Locale.Mask.Page.Create}
              bordered
              onClick={() => {
                const createdMaskTemplate = maskTemplateStore.create();
                setEditingMaskTemplateId(createdMaskTemplate.id);
              }}
            />
          </div>

          <div>
            {allMasksTemplate.map((m) => (
              <div className={styles["mask-item"]} key={m.id}>
                <div className={styles["mask-header"]}>
                  <div className={styles["mask-icon"]}></div>
                  <div className={styles["mask-title"]}>
                    <div className={styles["mask-name"]}>{m.name}</div>
                  </div>
                </div>
                <div className={styles["mask-actions"]}>
                  <IconButton
                    icon={<EditIcon />}
                    text={Locale.Mask.Item.Edit}
                    onClick={() => setEditingMaskTemplateId(m.id)}
                  />
                  <IconButton
                    icon={<DeleteIcon />}
                    text={Locale.Mask.Item.Delete}
                    onClick={async () => {
                      if (await showConfirm(Locale.Mask.Item.DeleteConfirm)) {
                        maskTemplateStore.delete(m.id);
                      }
                    }}
                  />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {editingMaskTemplateId && (
        <div className="modal-mask">
          <Modal title={"编辑面具模板"} onClose={closeMaskModal}>
            <MaskConfig
              mask={editingMask}
              updateMask={(updater) =>
                maskStore.updateMask(editingMaskTemplateId!, updater)
              }
            />
          </Modal>
        </div>
      )}
    </ErrorBoundary>
  );
}
